<!--
 * @Description: 兑换订单页面是公共的
-->
<template>
  <div class="exchange-order">
    <div class="exchange-order__header">
      <el-radio-group v-model="dataViewDate" @change="queryTradeOrderTotal()">
        <el-radio-button label="1">今天</el-radio-button>
        <el-radio-button label="3">最近三天</el-radio-button>
        <el-radio-button label="7">最近七天</el-radio-button>
        <el-radio-button label="4" class="el-radio-button-inner-datepicker">
          <el-date-picker v-model="dataViewRange" type="daterange" align="right" unlink-panels range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" :picker-options="pickerOptions"
            @focus="focusPickerDate" @change="changeDataViewDate"></el-date-picker>
        </el-radio-button>
      </el-radio-group>
    </div>

    <div class="exchange-order__total">
      <div id="order_total_flex">
        <div class="total_row_item">
          <div class="order_content">
            <div class="order_total_title">付款单（笔）</div>
            <div class="order_total_info">
              <span class="order_data">{{ totalData.paymentNumber }}</span>
            </div>
          </div>
          <div class="order_detail">
            <div class="order_content2">
              <div class="order_total_title">已完成</div>
              <div class="order_total_info">
                <span class="order_data">{{ totalData.completed }}</span>
              </div>
            </div>
            <div class="order_content2">
              <div class="order_total_title">待收货</div>
              <div class="order_total_info">
                <span class="order_data">{{ totalData.dispatched }}</span>
              </div>
            </div>
            <div class="order_content2">
              <div class="order_total_title">待发货</div>
              <div class="order_total_info">
                <span class="order_data">{{ totalData.waitReceiving }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="total_row_item">
          <div class="order_content">
            <div class="order_total_title">
              用户付款金额（元）
              <el-popover placement="top-start" width="200" trigger="hover" :content="getDatatime('消费者支付金额合计')">
                <el-button slot="reference" @click.stop style="padding:0;border:0"><i
                    class="el-icon-question"></i></el-button>
              </el-popover>
            </div>
            <div class="order_total_info">
              <span class="order_data">{{ totalData.paymentMon }}</span>
            </div>
          </div>
        </div>
        <div class="total_row_item">
          <div class="order_content">
            <div class="order_total_title">退款单（笔）</div>
            <div class="order_total_info">
              <span class="order_data">{{ totalData.refundNumber }}</span>
            </div>
          </div>
        </div>
        <div class="total_row_item">
          <div class="order_content">
            <div class="order_total_title">
              用户退款金额（元）
              <el-popover placement="top-start" width="200" trigger="hover" :content="getDatatime('消费者退款金额合计')">
                <el-button slot="reference" @click.stop style="padding:0;border:0"><i
                    class="el-icon-question"></i></el-button>
              </el-popover>
            </div>
            <div class="order_total_info">
              <span class="order_data">{{ totalData.refundMon }}</span>
            </div>
          </div>
        </div>
        <div class="total_row_item">
          <div class="order_content">
            <div class="order_total_title">
              用户成交金额（元）
              <el-popover placement="top-start" width="200" trigger="hover" :content="getDatatime('消费者确认收货已完成订单金额合计')">
                <el-button slot="reference" @click.stop style="padding:0;border:0"><i
                    class="el-icon-question"></i></el-button>
              </el-popover>
            </div>
            <div class="order_total_info">
              <span class="order_data">{{ totalData.turnover }}</span>
            </div>
          </div>
        </div>
        <div class="line_line"></div>
        <div class="total_row_item">
          <div class="order_content">
            <div class="order_total_title">累计付款用户数（人）</div>
            <div class="order_total_info">
              <span class="order_data">{{ totalData.accumulativeTotal }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="exchange-order__form">
      <el-form :inline="true" :model="formInline" class="demo-form-inline" @keyup.enter.native="search()"
        id="orderSearchForm">
        <el-form-item label="订单编号">
          <br />
          <el-input v-model="formInline.orderNo" placeholder style="margin-left:-70px;width:200px"></el-input>
        </el-form-item>
        <el-form-item label="会员姓名">
          <br />
          <el-input v-model="formInline.memberName" placeholder style="margin-left:-70px;width:200px"></el-input>
        </el-form-item>
        <el-form-item label="会员手机号">
          <br />
          <el-input v-model="formInline.memberPhone" placeholder style="margin-left:-80px;width:200px"></el-input>
        </el-form-item>
        <el-form-item label="店铺授权码">
          <br />
          <el-input v-model="formInline.authCode" placeholder style="margin-left:-82px;width:200px"></el-input>
        </el-form-item>
        <el-form-item label="商品名称">
          <br />
          <el-input v-model="formInline.goodsName" placeholder style="margin-left:-70px;width:200px"></el-input>
        </el-form-item>
        <el-form-item label="订单状态">
          <br />
          <el-select v-model="formInline.orderStatus" placeholder="请选择" clearable style="margin-left:-70px">
            <el-option v-for="(item, i) in orderStatusList" :key="i" :value="item.id" :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="type == 1" label="订单类型">
          <br />
          <el-select v-model="formInline.isDirectedExchange" placeholder="请选择" clearable style="margin-left:-70px">
            <el-option value="" label="全部"></el-option>
            <el-option :value="0" label="普通云币订单"></el-option>
            <el-option :value="1" label="定向云币订单"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间">
          <br />
          <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="yyyy-MM-dd" :picker-options="pickerOptions"
            style="margin-left: -70px;" />
        </el-form-item>
        <el-form-item label="订单客户编号">
          <br />
          <el-input v-model="formInline.orderCustomerCode" style="margin-left: -95px; width: 200px" placeholder="请输入订单客户编号" />
        </el-form-item>
        <el-form-item class="exchange-order__form--btn">
          <el-button type="primary" @click="search()" size="mini" icon="el-icon-search">查询</el-button>
          <el-button type="primary" @click="kong()" size="mini" icon="el-icon-delete">清空</el-button>
          <el-upload :action="action" :headers="headers" :show-file-list="false" :limit="1" :file-list="fileList"
            :before-upload="beforeUpload" :on-success="handleSuccess" :on-error="handleError" :disabled="uploadLoading"
            accept=".xls,.xlsx">
            <el-button type="warning" size="mini" icon="el-icon-edit" :loading="uploadLoading">批量发货</el-button>
          </el-upload>
          <el-button type="success" @click="exportExcel()" size="mini" icon="el-icon-s-data"
            :loading="exportLoading">导出</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="exchange-order__table">
      <el-table :data="tableData" :header-cell-style="{ background: '#eef1f6', color: '#606266' }" border
        v-loading="loading">
        <el-table-column type="index" label="序号" align="center" width="60"></el-table-column>
        <el-table-column label="订单编号" prop="orderNo" width="135px"></el-table-column>
        <el-table-column prop="orderCustomerCode" label="订单客户编号" align="center" :min-width="200"></el-table-column>
        <el-table-column label="会员手机号" prop="memberPhone" width="115px"></el-table-column>
        <el-table-column label="会员姓名" prop="memberName" with="100px"></el-table-column>
        <el-table-column label="收货人手机号" prop="postPersonTel" width="115px"></el-table-column>
        <el-table-column label="收货人姓名" prop="postPerson" width="100px"></el-table-column>
        <el-table-column label="收货地址" prop="postAddress" width="200px"></el-table-column>
        <el-table-column label="订单金额" prop="totalMoney"></el-table-column>
        <el-table-column label="商品名称" prop="goodsNames" width="150px"></el-table-column>
        <el-table-column label="商品数量" prop="totalAmount"></el-table-column>
        <el-table-column v-if="type == 1" :label="type == 1 ? '使用云币' : '使用酒币'">
          <template slot-scope="scope">
            {{ scope.row.totalMoney - scope.row.receivedMoney }}
          </template>
        </el-table-column>
        <el-table-column v-if="type == 1" label="订单类型">
          <template slot-scope="scope">
            {{ scope.row.isDirectedExchange == 0 ? '普通云币订单' : '定向云币订单' }}
          </template>
        </el-table-column>
        <el-table-column label="实付款" prop="receivedMoney"></el-table-column>
        <el-table-column label="店铺名称" prop="storeName"></el-table-column>
        <el-table-column label="支付类型">
          <template slot-scope="scope">
            {{ payTypeEnum[scope.row.payMethod] ? payTypeEnum[scope.row.payMethod] : '未知' }}
          </template>
        </el-table-column>
        <el-table-column label="订单状态" prop="orderStatus">
          <template slot-scope="scope">
            {{orderStatusList.find((item) => item.id == scope.row.orderStatus) ? orderStatusList.find((item) => item.id
              == scope.row.orderStatus).name : '未知' }}
          </template>
        </el-table-column>
        <el-table-column label="下单时间" prop="orderTime" width="150px"></el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="160">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="detailHandle(scope.row)">详情</el-button>
            <el-button v-if="scope.row.orderStatus == 1" type="text" size="mini"
              @click="sendHandle(scope.row)">发货</el-button>
            <el-button v-if="scope.row.orderStatus == 2" type="text" size="mini"
              @click="sendHandle(scope.row)">物流修改</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="block">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :page-sizes="[10, 20, 30, 50, 100, 150, 200]" :current-page="listQuery.current" :page-size="listQuery.size"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <SendGoodsDialog :show.sync="show" :detail="curDetail" @refresh="onRefresh" />
  </div>
</template>

<script>
import SendGoodsDialog from './SendGoodsDialog.vue';
import { queryOrderExchangeStatistics, queryOrderExchange, queryOrderExchangeExcel } from '@/api/exchangeOrder';
export default {
  components: {
    SendGoodsDialog,
  },
  props: {
    // 1 商家兑换订单（云币）， 0 消费者兑换订单（酒币）
    type: { type: [String, Number], default: '1' },
  },
  data() {
    return {
      dataViewDate: '1',
      dataViewRange: '',
      totalData: {
        orderNum: 0,
        paymentNumber: 0,
        refundNumber: 0,
        orderFinishNum: 0,
        orderAcceptNum: 0,
        orderPostNum: 0,
        orderCancelNum: 0,
        paymentMon: 0,
        refundMon: 0,
        payerNum: 0,
        accumulativeTotal: 0,
        turnover: 0,
      },
      pickerOptions: {
        shortcuts: [
          {
            text: '最近3天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
              picker.$emit('pick', [start, end]);
            },
          },
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            },
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            },
          },
        ],
      },
      loading: false,
      formInline: {
        orderNo: '',
        memberName: '',
        memberPhone: '',
        authCode: '',
        goodsName: '',
        orderStatus: '',
        beginDate: '',
        endDate: '',
        isDirectedExchange: '',
        orderCustomerCode: '',
      },
      dateRange: [],
      tableData: [],
      total: 0,
      listQuery: {
        current: 1,
        size: 100,
      },
      // 订单状态
      orderStatusList: [
        {
          id: '0',
          name: '待支付',
        },
        {
          id: '1',
          name: '待发货',
        },
        {
          id: '2',
          name: '待收货',
        },
        {
          id: '3',
          name: '已完成',
        },
        {
          id: '4',
          name: '已取消',
        },
        {
          id: '-1',
          name: '已退款',
        },
      ],
      // 付款方式
      payTypeEnum: {
        1: '现金支付',
        2: '货到付款',
        3: '线上支付',
        102: '酒币支付',
        105: '云币支付'
      },
      // 导出
      exportLoading: false,
      // 弹框相关
      show: false,
      curDetail: {},

      // 导入相关(上传图片相关配置)
      uploadLoading: false,
      fileList: [],
      headers: {
        token: localStorage.getItem('token')
      },
      action: `${process.env.VUE_APP_BASE_API}/api/trade-service/v1/myorder/orderExchangEximport`,
    };
  },
  created() {
    var nowDay = this.getNowDay();
    var beginDay = this.getMonthOneDay();
    this.dateRange = [beginDay, nowDay];
    this.getList()
    this.queryTradeOrderTotal();
  },
  methods: {
    search() {
      this.listQuery.current = 1;
      this.getList();
    },
    getList() {
      if (this.dateRange && this.dateRange.length > 0) {
        this.formInline.beginDate = this.dateRange[0];
        this.formInline.endDate = this.dateRange[1];
      } else {
        this.formInline.beginDate = '';
        this.formInline.endDate = '';
      }

      const data = {
        size: this.listQuery.size,
        current: this.listQuery.current,
        condition: {
          ...this.formInline,
          exchangeType: this.type == 1 ? 3 : 2,
        },
        ascs: [],
        descs: [],
      }
      this.loading = true
      queryOrderExchange(data).then(res => {
        this.tableData = res.records;
        this.total = res.total;
      }).finally(() => {
        this.loading = false
      })
    },
    onRefresh() {
      this.getList();
      this.curDetail = {};
    },
    kong() {
      this.formInline = this.$options.data().formInline;
    },
    handleSizeChange(val) {
      this.listQuery.size = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.current = val;
      this.getList();
    },
    // 导出
    exportExcel() {
      this.exportLoading = true;
      const data = {
        // size: this.listQuery.size,
        size: 10000000,
        current: this.listQuery.current,
        condition: {
          ...this.formInline,
          exchangeType: this.type == 1 ? 3 : 2,
        },
        ascs: [],
        descs: [],
      }
      queryOrderExchangeExcel(data).then(res => {
        const link = document.createElement('a');
        let blob = new Blob([res], { type: 'application/vnd.ms-excel' });
        link.style.display = 'none';
        //设置连接
        link.href = URL.createObjectURL(blob);
        link.download = `${this.type == 1 ? '商家' : '消费者'}兑换订单列表.xlsx`;
        document.body.appendChild(link);
        //模拟点击事件
        link.click();
        this.$message.success('导出成功');
      }).finally(() => {
        this.exportLoading = false;
      })
    },
    /* 获取时间+提示*/
    getDatatime(str) {
      return this.dataViewDate == 1
        ? '今天' + str
        : this.dataViewDate == 2
          ? '最近三天' + str
          : this.dataViewDate == 3
            ? '最近七天' + str
            : this.dataViewRange != null && this.dataViewRange != ''
              ? this.dataViewRange[0] + '至' + this.dataViewRange[1] + str
              : str;
    },
    // 切换订单的时间后的请求
    queryTradeOrderTotal() {
      const data = {
        type: this.type,
      }
      if (this.dataViewDate == '4') {
        data.beginDate = this.dataViewRange[0];
        data.endDate = this.dataViewRange[1];
      } else {
        data.dateType = this.dataViewDate
      }
      console.log('dataViewDate', this.dataViewDate)
      queryOrderExchangeStatistics(data).then(res => {
        this.totalData = res.result;
      })
    },
    //点击空白日期初始化
    focusPickerDate() {
      this.dataViewRange = '';
    },
    //点击头部时间选择切换为日期状态
    changeDataViewDate() {
      this.dataViewDate = '4';
      this.queryTradeOrderTotal();
    },

    // 导入相关
    beforeUpload() {
      this.uploadLoading = true;
    },
    handleError() {
      this.uploadLoading = false;
    },
    handleSuccess(res, file) {
      this.uploadLoading = false;
      this.fileList = [];
      this.$message.success('导入成功');
      this.onRefresh();
    },

    // 发货，修改发货
    sendHandle(row) {
      this.show = true;
      this.curDetail = row;
      // this.$emit('sendOrder', row);
    },
    detailHandle(row) {
      this.$router.push({
        name: "exchangeOrderDetail",
        params: {
          info: row,
          type: this.type
        }
      })
    },

    getNowDay() {
      var date = new Date();
      var seperator1 = '-';
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var strDate = date.getDate();
      if (month >= 1 && month <= 9) {
        month = '0' + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = '0' + strDate;
      }
      var currentdate = year + seperator1 + month + seperator1 + strDate;
      return currentdate;
    },
    getMonthOneDay() {
      var date = new Date();
      // 计算30天前的日期
      date.setDate(date.getDate() - 30);

      var seperator1 = '-';
      var year = date.getFullYear();
      var month = date.getMonth() + 1; // 月份从0开始，需+1
      var day = date.getDate();

      // 补零逻辑
      month = month.toString().padStart(2, '0'); // 始终补零到两位
      day = day.toString().padStart(2, '0');     // 日期补零

      var targetDate = year + seperator1 + month + seperator1 + day;
      return targetDate;
    },
  },
};
</script>

<style lang="scss" scoped>
.exchange-order {
  &__header {
    /deep/ .el-radio-button-inner-datepicker {
      .el-radio-button__inner {
        padding: 0;
      }

      .el-input__inner {
        border: none;
        height: 38px;
      }
    }
  }

  &__total {
    margin-top: 20px;

    #order_total_flex {
      display: flex;
      flex-direction: row;
      flex-wrap: nowrap;
      justify-content: space-around;

      /deep/ .order_content {
        cursor: pointer;
        width: 200px;
        padding: 20px 0;
        margin: 0 auto;
        text-align: center;
        overflow: hidden;
        border-radius: 4px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);

        .order_total_title {
          color: #000;
        }

        .order_total_info {
          margin-top: 10px;
        }

        .order_data {
          font-size: 1.4em;
          font-weight: bold;
        }
      }

      /deep/ .order_detail {
        width: 200px;
        margin-top: 10px;
        display: flex;
        flex-direction: row;
        flex-wrap: nowrap;
        justify-content: space-between;
      }

      /deep/ .order_content2 {
        width: 60px;
        cursor: pointer;
        padding: 10px 0;
        margin: 0 1px;
        text-align: center;
        overflow: hidden;
        border-radius: 4px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
      }
    }
  }

  &__form {
    margin-top: 30px;
    margin-left: 35px;

    &--btn {
      margin-top: 40px;

      /deep/ .el-form-item__content {
        display: flex;
        align-items: center;
        gap: 10px;

        .el-button {
          margin: 0;
        }
      }
    }

    /deep/ #orderSearchForm {
      margin-left: -30px;
      padding: 0;
      display: inline-block;
      text-align: left;
    }
  }

  .line_line {
    border-left: 5px solid #dddddd;
    display: inline-block;
    height: 6.25rem;
    margin-left: -1px;
    padding: 0px 0px 0px 3px;
  }
}
</style>
